<?php
/**
 * 商品属性管理模型
 * @author e5
 *
 */
class GoodsAttrModel extends Model{
	public $table = "goodsattr";
	/**
	 * 添加商品属性
	 * @param int $gid
	 */
	public function addGoodsAttr($gid){
		$taid = Q("post.taid",array());
		$gavalue = Q("post.attr",array());
		$addprice = Q("post.addprice",array());
		foreach ($taid as $k=>$v){
			if ($gavalue[$k] != ""){
				$this->data['gavalue'] = $gavalue[$k];
				$this->data['addprice'] = $addprice[$k];
				$this->data['vshop_typeattr_taid'] = $v;
				$this->data['vshop_goods_gid'] = $gid;
				$this->add();
			}
		}
	}
	/**
	 * 编辑商品属性
	 * @param int $gid
	 */
	public function editGoodsAttr($gid){
		//删除原商品属性
		$this->where("vshop_goods_gid={$gid}")->delete();
		//添加新商品属性
		$taid = Q("post.taid",array());
		$gavalue = Q("post.attr",array());
		$addprice = Q("post.addprice",array());
		foreach ($taid as $k=>$v){
			if ($gavalue[$k] != ""){
				$this->data['gavalue'] = $gavalue[$k];
				$this->data['addprice'] = $addprice[$k];
				$this->data['vshop_typeattr_taid'] = $v;
				$this->data['vshop_goods_gid'] = $gid;
				$this->add();
			}
		}
	}
	/**
	 * 通过商品id数组获得对应的商品属性
	 * @param array $gids
	 * @return array
	 */
	public function gidsGetAttrs($gids) {
		//查询商品属性
		$attr = $this->where('vshop_goods_gid IN ('.implode(",", $gids).')')->group('gavalue')->all();
		//重组查询结果数组(将同一类型的组合在一起，方便前台遍历)
		$temp = array();
		foreach ($attr as $v){
			$temp[$v['vshop_typeattr_taid']][] = $v;
		}
		//将类型属性名称压入数组
		$temp1 = array();
		$taModel = K("TypeAttr");
		foreach ($temp as $k=>$t){
			$temp1[] = array("taname"=>$taModel->where("taid={$k}")->getField("taname"),'value'=>$t);
		}
		return $temp1;
	}
	/**
	 * 通过筛选参数(商品属性id)过滤商品id
	 * @param array $param
	 * @param array $gids
	 */
	public function filerGids($param,$gids) {
		$gid = array();
		foreach ($param as $gaid){
			//如果没有选择"不限"
			if ($gaid){
				$gid[] = M()->join('__goodsattr__ ga1 JOIN __goodsattr__ ga2 ON ga1.gavalue=ga2.gavalue')->where("ga1.gaid={$gaid}")->getField('ga2.vshop_goods_gid',true);
			}
		}
		//如果存在没有选择"不限"的情况
		if ($gid){
			//取交集
			foreach ($gid as $k=>$v){
				//先将第一个元素取出
				if ($k == 0){
					$temp = $v;
				}else {
					//第一个各第二个取交集，获得的结果再和第三个取交集，以此类推
					$temp = array_intersect($gid[$k], $temp);
				}
			}
			//将筛选出的商品id数组再和传入的商品id数组(通过分类获得)取交集
			$gids = array_intersect($temp, $gids);
		}
		return $gids;
	}
}